package com.starblink.search.search.ui

import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FragmentUtils
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.search.SearchResultPageArgs
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.route.RoutePage
import com.starblink.rocketreserver.fragment.SearchWordVOF
import com.starblink.search.config.SearchConfig
import com.starblink.search.databinding.ActivitySearchBinding
import com.starblink.search.result.ui.ResultMainFragment
import com.starblink.search.search.ui.fragment.SearchHomeFragment

/**
 * 搜索主页
 */
@Route(path = RoutePage.Search.PAGE_SEARCH)
class SearchTVMActivity : BaseTVMActivity<ActivitySearchBinding, SearchVM>() {

    /**
     * JSON 序列化传值（效率较低，后期优化）
     */
    @JvmField
    @Autowired(name = RoutePage.Search.ARG_SHADING_WORD)
    var homeHint: SearchWordVOF? = null

    /**
     * JSON 序列化传值（效率较低，后期优化）
     */
    @JvmField
    @Autowired(name = RoutePage.Search.ARG_HOT_WORDS)
    var hotWords: List<SearchWordVOF>? = null

    /**
     * 直接到搜索结果页的关键词
     */
    @JvmField
    @Autowired(name = RoutePage.Search.ARG_KEY_WORD)
    var keyword: String? = null

    /**
     * 直接到搜索结果页的规则引擎id
     */
    @JvmField
    @Autowired(name = RoutePage.Search.GOOD_RULE_ID)
    var goodsRuleId: String? = null

    @JvmField
    @Autowired(name = RoutePage.Search.ARG_SCENE)
    var scene: Int = RoutePage.Search.SCENE.NORMAL.value

    @JvmField
    @Autowired(name = RoutePage.Search.ARG_HISTORY_TAG)
    var historyTag: String = ""

    private val sceneEnum: RoutePage.Search.SCENE
        get() = RoutePage.Search.SCENE.values().firstOrNull { it.value == scene }
            ?: RoutePage.Search.SCENE.NORMAL

    private val recFragment by lazyOnNone {
        SearchHomeFragment().apply {
            homeHint = this@SearchTVMActivity.homeHint
            hotWords = this@SearchTVMActivity.hotWords
            searchAction = { searchWord, composeSearchWord, searchWordSource, goodsRuleId ->
                toResult(searchWord, composeSearchWord, searchWordSource, goodsRuleId)
            }
            scene = this@SearchTVMActivity.sceneEnum
            historyTag = this@SearchTVMActivity.historyTag
        }
    }

    private var curTabIndex: Int? = null

    private val recFragmentTag = SearchHomeFragment::class.simpleName ?: "SearchHomeFragment"

    override fun initViewBinding(): ActivitySearchBinding =
        ActivitySearchBinding.inflate(layoutInflater)

    override fun initView() {
        super.initView()
        pageExposure(SpmPageDef.SearchRoute)
        if (keyword?.isNotEmpty() == true) {
            // 从首页带着搜索词进入，直接显示结果
            toResult(
                keyword!!,
                searchWordSource = SearchConfig.SearchWordSourceConfig.O_TYPE_SHADING,
                goodsRuleId = goodsRuleId
            )
        } else {
            addHomeFragment()
        }

        supportFragmentManager.addOnBackStackChangedListener {
            if (supportFragmentManager.backStackEntryCount == 0) {
                finish()
            }
        }

        setStatusBarBlackText()
    }

    private fun toResult(
        keyword: String,
        composeWords: List<String>? = null,
        searchWordSource: Int,
        goodsRuleId: String? = null
    ) {
        (navigationTo(RoutePage.Search.PAGE_SEARCH_RESULT) {
            extraOf(
                RoutePage.Search.ARG_SEARCH_RESULT to SearchResultPageArgs(
                    keyword = keyword,
                    composeWords = composeWords,
                    searchWordSource = searchWordSource,
                    scene = sceneEnum,
                    curTabIndex = curTabIndex,
                    goodsRuleId = goodsRuleId,
                )
            )
        } as ResultMainFragment?)?.let { it ->
            FragmentUtils.add(
                supportFragmentManager,
                it,
                viewBinding.fragmentContainer.id,
                false,
                true
            )
            FragmentUtils.show(it)
            it.textInputRequest = { str, curIndex ->
                val fragment = FragmentUtils.findFragment(supportFragmentManager, recFragmentTag)
                if (fragment == null) {
                    addHomeFragment()
                }
                FragmentUtils.hide(it)
                recFragment.inputFocus(str)
                curTabIndex = curIndex
            }
        }
    }

    private fun addHomeFragment() {
        FragmentUtils.add(
            supportFragmentManager,
            recFragment,
            viewBinding.fragmentContainer.id,
            recFragmentTag,
            false,
            true
        )
        FragmentUtils.show(recFragment)
    }

    fun showDialogLoading() {
        LoadingDialogManager.get().showLoading(this)
    }

    fun dismissDialogLoading() {
        LoadingDialogManager.get().dismissLoading()
    }


    companion object {
        const val TAG = "SearchTVMActivity"
    }

}